const {ccclass, property} = cc._decorator;

import {Snake} from "./Snake"
import {JoyStick} from "./../JoyStick"

@ccclass
class SnakeMgr extends cc.Component {


    @property(cc.Node)
    SnakePrefab:cc.Node;

    private playerSnaker:Snake;
    private _joyStick:JoyStick;

    public onLoad() {
        // init logic

    }

    public start() {
        this._joyStick = JoyStick.Instance;
        this.initPlayerSnake();
    }

    private initPlayerSnake() {
        let snake: cc.Node = cc.instantiate(this.SnakePrefab)
        this.playerSnaker = <Snake>snake.getComponent(Snake);
        this.playerSnaker.node.parent = this.node
        this.playerSnaker.node.active = true;
        this.playerSnaker.initSnake(cc.v2(0, 0), 10);

    }

    public update() {
        let direction  = this._joyStick.getDiretion();
        if (direction.mag() == 0) {
            return;
        }
        
        let targetDirection = cc.pAngle(direction, cc.v2(1, 0));
        if (direction.y < 0) {
            targetDirection *= -1;
        }
        if (targetDirection < 0) {
            targetDirection = 2 * Math.PI + targetDirection;
        }
        
        this.playerSnaker.targetDir = targetDirection;
    }
}
